
// 复制带随机指针的链表
// Created by madison on 2022/10/15.
//
#include "unordered_map"

using namespace std;

/*
// Definition for a Node.
 */
class Node {
public:
    int val;
    Node *next;
    Node *random;

    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};


class Solution {
public:
    // 方法一：回溯 + 哈希表
    unordered_map<Node *, Node *> cachedNode;

    Node *copyRandomList(Node *head) {
        if (head == nullptr) {
            return nullptr;
        }
        if (!cachedNode.count(head)) {
            Node *headNew = new Node(head->val);
            cachedNode[head] = headNew;
            headNew->next = copyRandomList(head->next);
            headNew->random = copyRandomList(head->random);
        }
        return cachedNode[head];
    }

    // 方法二：迭代 + 节点拆分
    Node *copyRandomList1(Node *head) {
        if (head == nullptr) {
            return nullptr;
        }
        for (Node *node = head; node != nullptr; node = node->next->next) {
            Node *nodeNew = new Node(node->val);
            nodeNew->next = node->next;
            node->next = nodeNew;
        }
        for (Node *node = head; node != nullptr; node = node->next->next) {
            Node *nodeNew = node->next;
            nodeNew->random = (node->random != nullptr) ? node->random->next : nullptr;
        }
        Node *headNew = head->next;
        for (Node *node = head; node != nullptr; node = node->next) {
            Node *nodeNew = node->next;
            node->next = node->next->next;
            nodeNew->next = (nodeNew->next != nullptr) ? nodeNew->next->next : nullptr;
        }
        return headNew;
    }
};

int main() {
    Solution solution;
    return 0;
}